package util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.StarMicronics.StarIOSDK.logic.Config;

public class Util_Convert {

	/** Bitmap → byte[] */
	public static byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		return baos.toByteArray();
	}

	/** byte[] → Bitmap */
	public static Bitmap Bytes2Bimap(byte[] b) {
		if (b.length != 0) {
			return BitmapFactory.decodeByteArray(b, 0, b.length);
		} else {
			return null;
		}
	}

	public static void saveMyBitmap(String bitName, Bitmap bitmap) throws IOException {
		File f = new File(Config.fileOperationInSDCardPath, bitName + ".jpg");
		f.createNewFile();
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 替换数组中的元素
	 * 
	 * @param content
	 * @param olds
	 * @param news
	 * @return
	 */
	public final static String replace(String content, String olds, String news) {
		int index = 0;
		while (true) {
			index = content.indexOf(olds, index);
			if (index == -1)
				break;
			content = content.substring(0, index) + news + content.substring(index + olds.length());
			index += news.length();
		}
		return content;
	}

	/** 质量压缩 */
	private Bitmap compressImage(final Bitmap image) {
		int options = 100;
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中

		// TODO Auto-generated method stub
		while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
			System.out.println("options--->>" + options + "   baos--->>" + (baos.toByteArray().length / 1024) + "k");

			baos.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
			options -= 10;// 每次都减少10
		}

		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		System.out.println("size---->" + isBm.available() / 1024.0);
		Util_File.writeFile(baos.toByteArray(), "appp.jpg", Context.MODE_PRIVATE);
		return bitmap;
	}
}
